package com.nullpointer.playerinfo.bukkit.events;

import java.sql.SQLException;
import java.util.UUID;

import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.scheduler.BukkitRunnable;

import com.nullpointer.playerinfo.bukkit.PlayerInfoBukkit;
import com.nullpointer.playerinfo.bukkit.objects.BukkitTimer;
import com.nullpointer.playerinfo.common.Base;
import com.nullpointer.playerinfo.common.objects.Player;

public class PlayerJoin implements Listener {
    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent e) {

        org.bukkit.entity.Player bukkitPlayer = e.getPlayer();
        UUID playerUUID = bukkitPlayer.getUniqueId();

        new BukkitRunnable() {


            @Override
            public void run() {
                Player player;
                try {
                    if (PlayerInfoBukkit.mysql.havePlayer(playerUUID)) {
                        player = PlayerInfoBukkit.mysql.getPlayer(playerUUID);
                    
                        if (System.currentTimeMillis() - player.getLastPlayTime() > PlayerInfoBukkit.reconnectionTime) { // 判断玩家是否掉线
                            player.setOnlineTime(0);
                        }

                    } else {
                        player = new Player(bukkitPlayer.getName(), bukkitPlayer.getUniqueId());
                    }
                    Base.playerMap.put(playerUUID, player);

                    BukkitTimer timer = new BukkitTimer(player);
                    timer.runTaskTimerAsynchronously(PlayerInfoBukkit.plugin, 0L, 20L);
                    player.setPlayerTimerTaskId(timer.getTaskId());

                    PlayerInfoBukkit.mysql.savePlayer(player);

                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            
        }.runTaskAsynchronously(PlayerInfoBukkit.plugin);


    }
}
